<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/27
 * Time: 3:53 PM
 */
namespace app\backend\modules\content\controllers;

use app\backend\controllers\BaseController;
use app\backend\modules\content\services\ArticleService;
use app\backend\modules\sys\services\ThemeService;
use app\common\events\content\ArticleCreatedEvent;
use app\common\events\content\ArticleDeletedEvent;
use app\common\events\content\ArticleUpdatedEvent;
use app\common\models\Article;
use app\common\models\ArticleTag;
use app\common\models\Tag;
use app\common\models\ThemeFile;
use Illuminate\Support\Facades\DB;


class ArticleController extends BaseController
{
    public function index(){
        return view("backend.content.article.index");
    }
    public function getList(){
        $search = request()->search;
        $list = (new ArticleService())->getList($search);
        return $this->successJson('',$list);
    }
    public function changeStatus()
    {
        $id = request()->id;
        $type = request()->type;
        $model = Article::site()->select()
            ->where('id',$id)
            ->first();
        if (empty($model)) {
            return $this->errorJson('未找到数据');
        }
        switch ($type){
            case 'is_publish':
                $status=Article::STATUS_YES;
                if($model->is_publish==Article::STATUS_YES){
                    $status= Article::STATUS_NO;
                }
                $model->is_publish = $status;
                break;
            case 'is_recommend':
                $status=Article::STATUS_YES;
                if($model->is_recommend==Article::STATUS_YES){
                    $status= Article::STATUS_NO;
                }
                $model->is_recommend = $status;
                break;
            case 'is_top':
                $status=Article::STATUS_YES;
                if($model->is_top==Article::STATUS_YES){
                    $status= Article::STATUS_NO;
                }
                $model->is_top = $status;
                break;
        }
        $model->save();
        event(new ArticleUpdatedEvent($model));
        return $this->successJson();
    }
    public function detail(){
        return view("backend.content.article.detail");
    }
    public function getDetail(){
        $id = intval(request()->id);
        $res['info'] = [];
        $res['publish_time'] =  date('Y-m-d H:i:s');
        $res['tag_ids_arr'] = [];
        $res['tag_list'] = [];
        if($id){
            $model = Article::site()->select()
                ->where('id',$id)
                ->first();
            if (empty($model)) {
                return $this->errorJson('未找到数据');
            }
            $model->publish_time = date('Y-m-d H:i:s',$model->publish_time);
            $model->thumb = fmt_media_url($model->thumb);
            $res['info'] = $model;
            $res['tag_ids_arr'] = array_map('intval',array_filter(explode(',',$model['tag_ids'])));
            $tag_list = Tag::site()->select('id','name')
                ->whereIn('id',$res['tag_ids_arr'])
                ->get();
            if($tag_list){
                $res['tag_list'] = $tag_list;
            }
        }
        $themeService = new ThemeService();
        $themeFiles = $themeService->getDefaultTypeFiles();
        $res['pc_detail_tpl_list'] = $themeFiles['pc'][ThemeFile::TYPE_ARTICLE_DETAIL];
        $res['h5_detail_tpl_list'] = $themeFiles['h5'][ThemeFile::TYPE_ARTICLE_DETAIL];
        return $this->successJson('',$res);
    }
    public function create(){
        $data = request()->params;
        $data['site_id'] = \YunCms::siteId();
        $data['user_id'] = \YunCms::$adminUid;
        $data['pid'] = intval($data['pid']);
        $data['display_order'] = intval($data['display_order']);
        if(!$data['publish_time']){
            //默认当前时间
            $data['publish_time'] = time();
        }else{
            $data['publish_time'] = strtotime($data['publish_time']);
        }
        $model = new Article();
        $model->fill($data);
        $validator = $model->validator();
        if ($validator->fails()) {
            return $this->errorJson($validator->messages());
        } else {

            DB::transaction(function() use ($model,$data){
                $model->save();
                $tagIds = explode(',',$data['tag_ids']);
                if(!$tagIds[0]){

                }
                $model->tags()->sync(array_filter(explode(',',$data['tag_ids'])));
                $parentPath = '0';
                if ($data['pid']) {
                    $parentModel = Article::select(['id','path'])
                        ->where('id',$data['pid'])
                        ->first();
                    if($parentModel['path']){
                        $parentPath = $parentModel['path'];
                    }
                }
                $model->path = $parentPath.'-'.$model->id;
                $model->save();
            });
            event(new ArticleCreatedEvent($model));
            return $this->successJson();
        }
    }
    public function update(){
        $data = request()->params;
        $id = $data['id'];
        $data['pid'] = intval($data['pid']);
        $data['display_order'] = intval($data['display_order']);
        if(!$data['publish_time']){
            //默认当前时间
            $data['publish_time'] = time();
        }else{
            $data['publish_time'] = strtotime($data['publish_time']);
        }
        $model = Article::find($id);
        if (empty($model)) {
            $this->errorJson('未找到数据');
        }
        $model->fill($data);
        $validator = $model->validator();
        if ($validator->fails()) {
            return $this->errorJson($validator->messages());
        } else {
            DB::transaction(function() use ($model,$data){
                $model->save();
                $model->tags()->sync(array_filter(explode(',',$data['tag_ids'])));
                $oldPath = $model['path'];
                $id = $model['id'];
                $path = '0-'.$id;
                if ($data['pid']) {
                    $parentModel = Article::site()->select(['id','path'])
                        ->where('id',$data['pid'])
                        ->first();
                    if($parentModel['path']){
                        $path = $parentModel['path'].'-'.$id;
                    }
                }
                $model->path = $path;
                $model->save();
                //修改子文章path信息
                //如父文章path=0-2-5，子文章path=0-2-5-9
                $children = Article::site()->select(['id','path'])
                    ->where('path','like',$model['path'].'-%')
                    ->get();
                foreach ($children as $child){
                    //循环修改子文章，一般不会太多
                    $childPath = str_replace($oldPath . '-', $path . '-', $child['path']);
                    Article::where('id', $child['id'])->update(['path' => $childPath]);
                }
            });
            event(new ArticleUpdatedEvent($model));
            return $this->successJson();
        }
    }
    public function delete()
    {
        $id = request()->id;
        $model = Article::find($id);
        if(!$model){
            return $this->errorJson('未找到数据');
        }
        DB::transaction(function() use ($model,$id){
            $model->delete();
            ArticleTag::where('article_id',$id)->delete();
        });
        event(new ArticleDeletedEvent($id));
        return $this->successJson();
    }
    /**
     * 检索文章
     */
    public function query(){
        $kwd = trim(request()->kwd);
        $exceptId = intval(request()->except_id);
        $list = Article::site()->select(['id','title']);
        if($kwd){
            $list = $list->where('title','like','%'.$kwd.'%');
        }
        if($exceptId){
            $list = $list->where('id','<>',$exceptId);
        }
        $list = $list
            ->orderBy('id', 'desc')
            ->take(100)
            ->get();
        return $this->successJson('',$list);
    }
}